// pages/index/discuss/discuss.js
const utils = require('../../../utils/util.js');
const glob = getApp().globalData;
const nim = require('../../../utils/chatroom.js');
import {defaultPic} from "../../../utils/imgbase64.js";
const screenSize = wx.getSystemInfoSync().windowHeight;
Page({
  /**
   * 页面的初始数据
   */
  data: {
      canUser: true,
      // 用户输入内容
      userText: "",
      // 用户评论按钮
      userDis: true,
      //用户消息数组
      bubbleList:[],
      //当前显示消息Id
      scrollId:'',
      //当前滚动高度
      scrollHeight:0,
      //最大滚动高度
      maxScroll:0,
      isScroll:true,
      lid:"",
      quetyId:"",
      //路演是否已完成
      isComplete:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
      if(options.type =="old"){
        this.setData({
          isComplete:true
        })
      }
      this.setData({
          defaultPic,
          role:options.role,
          queryId: options.queryId
      })
      this.roomid = options.roomid;
      this.room_addr = JSON.parse(options.room_addr);
      wx.setNavigationBarTitle({
          title: options.title
      })   
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
      //判断版本兼容
      wx.getSystemInfo({
          success: (res) => {
              let arr = res.SDKVersion.split('.')
              let num = parseInt(arr[0]) * 10 + parseInt(arr[1])
              if (num < 19) {
                  this.setData({
                      canUser: false
                  })
              }
          }
      })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
      //判断是否登录
      let app = getApp();
      app.loginState();
      // console.log("开始连接")
      // console.log(new Date().getTime())
      let user = wx.getStorageSync('user_info');
      new nim.Chatroom({
          account: user.accid,
          token: user.token,
          roomId: this.roomid,
          roomAddr: this.room_addr,
          onconnect: this.roomConnect,
          onerror: this.roomError,
          onmsgs: this.roomMsgs,
          ondisconnect: res => {
              this.setData({
                  bubbleList: []
              })
          }
      })
  },
  //聊天室连接成功
  roomConnect: function (info) {
      console.log("连接成功")
      this.getHistory(1, true);
  },
  //聊天室连接失败
  roomError: function (err) {
      console.log('err', err)
  },
  //消息视图滚动
  viewScroll:function(e){
    this.setData({
        scrollHeight:e.detail.scrollTop,
        maxScroll:e.detail.scrollHeight
    })
  },
  //滚动到顶部
  scrollUpper:function(){
      this.getHistory("",false);
  },
  //用户消息模块
  //监听用户输入
  userInp: function (e) {
      this.setData({
          userText: e.detail.value
      })
      if (e.detail.cursor > 0) {
          this.setData({
              userDis: false
          })
      } else {
          this.setData({
              userDis: true
          })
      }
  },
  //用户评论
  userSend: function () {
      let str = this.data.userText;
      let opt = {
          type: 'text',
          content: str,
          custom: {
              role: this.data.role
          }
      }
      this.setData({
          userText: '',
          userDis: true
      })
      this.sendRoomMsgs(opt);
  },
  //聊天室发送消息
  sendRoomMsgs: function (opt) {
      //发送文本消息
      if (opt.type == 'text') {
          let msg = {
              text: opt.content,
              idClient: opt.idClient || "",
              resend: opt.resend || false,
              custom: JSON.stringify(opt.custom),
              done: this.sendMsgsResult
          }
          glob.nim.sendText(msg)
      }
  },
  //获取历史记录
  getHistory:function(page,bol){
      wx.showLoading();
      utils.ajax(glob.ROOT_URL + 'demosts/' + this.data.queryId + '/replies', {
          header: {
              "Accept": "application/vnd.dct.v1+json"
          },
          data: {
              lid: this.data.lid,
              from: "0",
              uid: wx.getStorageSync("user_info").uid
          }
      }, res => {
          wx.hideLoading();
          if (res.state == "1") {
              if (res.data.length < 1) {
                  if (bol == false) {
                      wx.showToast({
                          title: '没有更多历史记录~',
                          icon: "none"
                      })
                  }
               } else {
                  let data = res.data.reverse();
                  this.setData({
                      lid:data[data.length-1].id
                  })
                  data.map((item, index) => {
                     if (item.long == "1") {
                          item.showTime = "1";
                          item.date = utils.showMsgDate(Number(item.userUpdateTime));
                          this.setData({
                              showTime: Number(item.userUpdateTime)
                          })
                      }
                      this.data.bubbleList.unshift(item);
                  })
                  this.setData({
                      bubbleList: this.data.bubbleList
                  })
                  if (bol == true) {
                      this.scrollBottom(this.data.bubbleList[this.data.bubbleList.length-1].idClient,true);
                  }
              }
          } else {
                wx.hideLoading();
                wx.showToast({
                    title: '获取历史记录失败,请重试',
                    icon: "none"
                })
            }
          }, err => {
              this.isTop = true;
              wx.showToast({
                  title: '获取历史记录失败，网络错误',
                  icon: "none"
              })
        })
  },
  //消息发送结果
  sendMsgsResult: function (err, msg) {
      if (!err) {
          let role = JSON.parse(msg.custom).role;
          let user = wx.getStorageSync('user_msg');
          //验证身份，0为普通用户
          if (role == 0) {
              msg.fromNick = user.nickname;
              msg.fromAvatar = user.avatar;
              console.log(msg)
              this.data.bubbleList.push(msg);
              this.setData({
                  bubbleList: this.data.bubbleList
              })
              this.scrollBottom(msg.idClient,true);
           }
        } else {
          wx.showToast({
              title: '消息发送失败，请重试~',
              icon: "none"
          })
      }
  },
  //聊天室收到消息
  roomMsgs: function (msgs) {
      if (msgs[0].type == "notification") {
          console.log("none")
      } else {
          let role = JSON.parse(msgs[0].custom);
          if (role.role == 0) {
              this.data.bubbleList.push(msgs[0]);
              this.setData({
                  bubbleList: this.data.bubbleList
              })
          }
          this.scrollBottom(msgs[0].idClient,false)
      }
  },
  //滚动到底部
  scrollBottom:function(e,bol){
      if(bol==true){
          //用户主动发消息直接滚动底部
          scroll(this)
      }else{
          //判断两次滚动位置
          let now = this.data.scrollHeight,max = this.data.maxScroll;
          if(max-now<=screenSize){
              scroll(this)
          }
      }
      function scroll(page){
          let str = "msg" + e;
          page.setData({
              scrollId: str
          })
      }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
      console.log("退出")
      glob.nim.disconnect();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
      glob.nim.disconnect();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  }
})